package xj.toolkit.netty.handler.codec.http.transformer;

import io.netty.handler.codec.http.FullHttpRequest;

import org.apache.commons.collections4.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xj.toolkit.base.Sender;
import xj.toolkit.netty.transport.TransportUtils;
import xj.toolkit.netty.util.NettyConstants;
import xj.toolkit.util.MutablePropertyable;
import xj.toolkit.util.Propertyable;
import xj.toolkit.util.PropertyableUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author hp
 *
 */
public class CopyRequestPropertyTransformer implements HttpRequestTransformer {

	private static final Logger logger = LoggerFactory.getLogger(CopyRequestPropertyTransformer.class);

	private Transformer impl;
	private String[] copyedProperties;

	/**
	 * @param impl
	 *            the impl to set
	 */
	public void setImpl(Transformer impl) {
		this.impl = impl;
	}

	public void setCopyedProperties(List<String> propertyNames) {
		this.copyedProperties = propertyNames.toArray(new String[propertyNames.size()]);
	}

	public List<String> getCopyedProperties() {
		return Arrays.asList(copyedProperties);
	}

	@Override
	public Object transform(FullHttpRequest request) {
		Object bean = impl.transform(request);
		if (null == bean) {
			return null;
		}

		if (bean instanceof MutablePropertyable) {

			MutablePropertyable propertyable = (MutablePropertyable) bean;
			PropertyableUtils.copyProperties((Propertyable) request, propertyable, copyedProperties);

			propertyable.setProperty(NettyConstants.PROPERTY_ORIGINAL_HTTP_REQUEST, request);

			Sender<?> sender = TransportUtils.getSenderOf((MutablePropertyable<String, Object>)request);
			if (sender != null) {
				TransportUtils.attachSender(propertyable, sender);
			}

		}

		return bean;
	}

}
